/*
 * @Author: Kiro AI Assistant
 * @Date: 2025-01-10
 * @Description: 网络工具类 - 提供网络请求的通用工具方法
 */

import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import '../services/music_api_exception.dart';

/// 网络工具类
/// 提供网络请求的通用处理方法
class NetworkUtils {
  /// 处理Dio异常并转换为自定义异常
  static Exception handleDioException(DioException error) {
    switch (error.type) {
      case DioExceptionType.connectionTimeout:
        return const NetworkException('连接超时，请检查网络连接');
      case DioExceptionType.sendTimeout:
        return const NetworkException('请求发送超时');
      case DioExceptionType.receiveTimeout:
        return const NetworkException('响应接收超时');
      case DioExceptionType.badResponse:
        final statusCode = error.response?.statusCode;
        if (statusCode != null) {
          switch (statusCode) {
            case 400:
              return const NetworkException('请求参数错误');
            case 401:
              return const PermissionException('未授权访问');
            case 403:
              return const PermissionException('访问被禁止');
            case 404:
              return const NetworkException('请求的资源不存在');
            case 429:
              return const NetworkException('请求过于频繁，请稍后再试');
            case 500:
              return const ServiceUnavailableException('服务器内部错误');
            case 502:
              return const ServiceUnavailableException('网关错误');
            case 503:
              return const ServiceUnavailableException('服务暂时不可用');
            default:
              return NetworkException('网络请求失败 (HTTP $statusCode)');
          }
        }
        return const NetworkException('网络请求失败');
      case DioExceptionType.cancel:
        return const NetworkException('请求已取消');
      case DioExceptionType.connectionError:
        return const NetworkException('网络连接错误，请检查网络设置');
      case DioExceptionType.badCertificate:
        return const NetworkException('证书验证失败');
      case DioExceptionType.unknown:
      default:
        return NetworkException('网络请求异常: ${error.message}');
    }
  }

  /// 检查响应是否成功
  static bool isResponseSuccessful(Response response) {
    return response.statusCode != null &&
        response.statusCode! >= 200 &&
        response.statusCode! < 300;
  }

  /// 获取用户友好的错误消息
  static String getUserFriendlyErrorMessage(Exception error) {
    if (error is NetworkException) {
      return error.message;
    } else if (error is AudioException) {
      return error.message;
    } else if (error is SearchException) {
      return error.message;
    } else if (error is PlayUrlException) {
      return error.message;
    } else if (error is ParseException) {
      return '数据解析失败，请重试';
    } else if (error is PermissionException) {
      return error.message;
    } else if (error is ServiceUnavailableException) {
      return error.message;
    } else {
      return '操作失败，请重试';
    }
  }

  /// 判断是否为网络相关错误
  static bool isNetworkError(Exception error) {
    return error is NetworkException ||
        error is ServiceUnavailableException ||
        error is PermissionException;
  }

  /// 判断错误是否可以重试
  static bool isRetryableError(Exception error) {
    if (error is NetworkException) {
      return error.message.contains('超时') ||
          error.message.contains('连接') ||
          error.message.contains('网络');
    }
    if (error is ServiceUnavailableException) {
      return true;
    }
    return false;
  }

  /// 创建标准的请求选项
  static Options createStandardOptions({
    Map<String, dynamic>? headers,
    ResponseType? responseType,
    String? contentType,
    Duration? sendTimeout,
    Duration? receiveTimeout,
  }) {
    final Map<String, dynamic> defaultHeaders = {
      'User-Agent':
          'Mozilla/5.0 (Linux; U; Android 8.1.0; zh-cn; BLA-AL00 Build/HUAWEIBLA-AL00) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/57.0.2987.132 MQQBrowser/8.9 Mobile Safari/537.36',
    };

    if (headers != null) {
      defaultHeaders.addAll(headers);
    }

    return Options(
      headers: defaultHeaders,
      responseType: responseType ?? ResponseType.json,
      contentType: contentType,
      sendTimeout: sendTimeout,
      receiveTimeout: receiveTimeout,
    );
  }

  /// 记录网络请求日志
  static void logRequest(String method, String url,
      {Map<String, dynamic>? params}) {
    if (kDebugMode) {
      debugPrint('🌐 [$method] $url');
      if (params != null && params.isNotEmpty) {
        debugPrint('📝 参数: $params');
      }
    }
  }

  /// 记录网络响应日志
  static void logResponse(Response response) {
    if (kDebugMode) {
      debugPrint('✅ [${response.statusCode}] ${response.requestOptions.uri}');
      if (response.data != null) {
        final dataLength = response.data.toString().length;
        debugPrint('📦 响应数据长度: $dataLength');
      }
    }
  }

  /// 记录网络错误日志
  static void logError(String operation, Exception error) {
    if (kDebugMode) {
      debugPrint('❌ $operation 失败: $error');
    }
  }
}
